package br.com.comanda.service;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;
import br.com.comanda.restclient.RestClient;
import br.com.comanda.util.WebServiceUtil;
import br.com.comanda.vos.Product;

public class ProductService {

	public List<Product> readAllProducts() {
		RestClient client = new RestClient();
		String result = client.getRESTFileContent(WebServiceUtil.URL + "products");

		Log.i("INFO", result);

		List<Product> productVOs = new ArrayList<Product>();
		try {
			JSONObject productsJsonResult = new JSONObject(result);
			JSONArray productsJson = productsJsonResult.getJSONArray("product");

			JSONObject productJson = null;
			Product productVO = null;

			for (int i = 0; i < productsJson.length(); i++) {
				productJson = new JSONObject(productsJson.getString(i));

				Log.i("PRODUCT NAME: ", productJson.getString("name"));

				productVO = new Product(productJson.getLong("id"), productJson.getString("name"), (float) productJson.getDouble("price"),
						productJson.getString("description"));

				productVOs.add(productVO);
			}

			return productVOs;

		} catch (Exception e) {
			Log.i("ERROR", e.getMessage());
			return productVOs;
		}
	}
}
